package org.metasketch.editor.toolbox;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.metasketch.editor.toolbox.advanced.ISemanticTypeTester;
import org.metasketch.model.CommonIdentified;

public class ToolHandlerRegistry {

	Map<String, IToolHandler> toolHandlerPerType = new HashMap<String, IToolHandler>();

	Map<Class, List<IToolHandler>> toolHandlerPerClass = new HashMap<Class, List<IToolHandler>>();

	public void register(String type, IToolHandler toolHandler) {
		// if (toolHan)
		toolHandlerPerType.put(type, toolHandler);
	}

	public IToolHandler get(String name) throws Throwable {
		return toolHandlerPerType.get(name);

	}

	public void register(Class type, IToolHandler toolHandler) {
		// if (toolHan)
		List<IToolHandler> list = toolHandlerPerClass.get(type);
		if (list == null) {
			list = new ArrayList<IToolHandler>();
			toolHandlerPerClass.put(type, list);
		}

		list.add(toolHandler);
	}

	public IToolHandler get(Class type) throws Throwable {
		List<IToolHandler> list = toolHandlerPerClass.get(type);
		if (list == null || list.size() == 0)
			return null;

		if (list.size() == 1)
			return list.get(0);

		return null;
	}

	public IToolHandler get(CommonIdentified semantic) throws Throwable {
		IToolHandler handler = get(semantic.getClass());
		if (handler != null)
			return handler;

		List<IToolHandler> list = toolHandlerPerClass.get(semantic.getClass());
		if (list.size() <= 1)
			return null;

		for (IToolHandler iToolHandler : list) {
			if (iToolHandler instanceof ISemanticTypeTester) {
				ISemanticTypeTester tester = (ISemanticTypeTester) iToolHandler;
				if (tester.isValid(semantic))
					return iToolHandler;
			}
		}

		// return the last one
		return list.get(list.size() - 1);
	}

}
